
import 'dart:async';

import 'package:event_bus/event_bus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:rfid/page/index_page.dart';
import 'package:rfid/socket/socket.dart';
import 'package:rfid/socket/socket_helper.dart';
import 'package:rfid/tts/tts_helper.dart';
import 'package:bot_toast/bot_toast.dart';

import 'entity/book_entity.dart';
import 'entity/current_task_entity.dart';
import 'entity/setting_entity.dart';
import 'http/api_url.dart';
import 'log/logger_manager.dart';
import 'util/camera_util.dart';
import 'util/timer_manager.dart';


void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await GetStorage.init();

  await Hive.initFlutter();
  Hive.registerAdapter(BookEntityAdapter());

  books = await Hive.openBox('books');
  // books.deleteFromDisk();
  tts = TtsHelper()..initTTS();
  await LoggerManager().initLogger();
  eventFactory = EventBus();
  final box = GetStorage();
  timer = TimerManager();
  currentTask = CurrentTaskEntity();
  if(box.hasData('setting_entity')){
    settingEntity = SettingEntity.fromJson(box.read("setting_entity"));
    if(settingEntity.apiAddr != null){
      apiUrl = 'http://${settingEntity.apiAddr!}:60060';
      faceUrl = 'http://${settingEntity.apiAddr!}:10040';

    }
    // if(settingEntity.faceApiAddr != null){
    //   faceUrl = settingEntity.faceApiAddr!;
    // }
    if(settingEntity.picApiAddr != null){
      picUrl = 'http://${settingEntity.picApiAddr!}:60040';
    }
    if(settingEntity.appKey != null){
      appKey = settingEntity.appKey!;
    }
    if(settingEntity.webSocketAddr != null){
      websocket = settingEntity.webSocketAddr!;
    }
    if(settingEntity.kdApi != null){
      kdFaceUrl = 'http://${settingEntity.kdApi!}';
    }

  }else{
    settingEntity = SettingEntity();
  }
  if(websocket!=null && websocket != ""){
    socketHelper = SocketHelper(websocket!);
  }

  FlutterError.onError = (FlutterErrorDetails details) async {
    LoggerManager().write("error", '${details.exception}\r\n${details.stack}');
  };
  //
  runZonedGuarded(() {
    runApp(const MyApp());
  }, (Object error, StackTrace stack) {
      print('$error $stack');
  });
  // runApp(const MyApp());

}

late EventBus eventFactory;
late SocketHelper socketHelper;
late SettingEntity settingEntity;
late Box books;
late TtsHelper tts;
late TimerManager timer;
late CurrentTaskEntity currentTask;
CameraUtil camera = CameraUtil();
String version = '2.5.7';
int versionCode = 4;

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return  ScreenUtilInit(
      designSize: const Size(360, 640),
      minTextAdapt: true,
      splitScreenMode: true,
      builder: (_ , child) {
        return  GetMaterialApp(
            debugShowCheckedModeBanner: false,
            theme: ThemeData(
              fontFamily: 'simsun',
            ),
            routingCallback: (routing){
              if(routing!.current == '/'){
                camera.disposeCurrentCamera();
              }
            },
            builder: BotToastInit(),
            home: const Index()
        );
      },
    );
  }
}
